$(document).ready(function (){
    $("#gestisciCategorie").dialog({
        show: "blind",
        hide: "explode",
        height: 400,
        width: 600,
        modal: true
    }
    );

    $("#sub").click(function(){
        if($("#sub:checked").length == 1){
            $('#padre').attr("disabled", false);
            caricaCategorie();
        }
        else {
            $('#padre').attr("disabled", true);
        }
    });

    $("#addCategoriaForm").submit(function(){
        startLoading();
        $("#addCategoriaForm input[type=submit]").val("Salvataggio...");
        $("#addCategoriaForm input[type=submit]").attr("disabled", "disabled");
        $.getJSON(server_home + 'c/add.json', {
            name: $("#gestisciCategorie #nome").val(),
            id_region: $("#gestisciCategorie #regioni").val(),
            id_language: $("#gestisciCategorie #lingue").val(),
            id_padre: $("#padre").val()
        }, function(data){
            $("#addCategoriaForm input[type=submit]").val("Aggiungi");
            if(data.error == undefined){
                $("#result").show();
                $("#result").html("Categoria <a href=\"" + data.address + "\">" + data.name + "</a> aggiunta");
                $("#addCategoriaForm input[type=submit]").attr("disabled", false);
                caricaCategorie();
                stopLoading();
            }
            else {
                alert("Errore: " + data.error);
                $("#addCategoriaForm input[type=submit]").attr("disabled", false);
            }
        });
        return false;
    });
    $('#nazioni').change(function(){
        caricaRegioni($("#nazioni").val());
    });
});
function caricaCategorie(){
    startLoading();
    $("#padre").children().remove();
    $.getJSON(server_home + 'c/getAll.json',
    {
        // no params
    },
    function(data) {
        $.each(data.categories, function(key, val) {
            $('#padre').append("<option value='"+val.id+"'>"+val.country+" -> "+val.region+" -> "+val.language+" - "+val.name+"</option>");
        });
    });
    stopLoading();
}
function caricaRegioni(nazione){
    startLoading();
    $("#regioni").children().remove();
    $.getJSON(server_home + 'country/getregions.json',
    {
        id_country: nazione
    },
    function(data) {
        $.each(data.regions, function(key, val) {
            $('#regioni').append("<option value='"+val.id+"'>"+val.name+"</option>");
        });
    });
    stopLoading();
}